
$(document).ready(function() {Goon.Init(); });

var Goon = (function(){
	
	var Init = function(){
		$('#newGoonContainer').find('input[type="button"][name="save"]').on('click', addClick);
		$('#newGoonContainer').find('input[type="button"][name="saveJSON"]').on('click', addJSONClick);
	
		getList();
	};
	
	var getList = function(){
		var listURL = $('#listGetURL').val();
		jQuery.ajax( listURL, 
				{ success: getListSuccess, 
				  error: Utils.AjaxFail
				});
	};
	
	var getListSuccess = function(data, textStatus, jqXHR){
		$('#listContainer').html(data);
		$('[name="btnDetail"]').on('click', detailClick);
	};
	
	var detailClick = function(eventObject){
		
		var detailsURL = $(eventObject.srcElement).siblings('[name="detailsURL"]').val();
		jQuery.ajax( detailsURL, 
				{ success: getDetailsSuccess, 
				  error: Utils.AjaxFail
				});
	};
	
	var getDetailsSuccess = function(data, textStatus, jqXHR) {
		
		$('#detailsContainer').html(data);
	};

	var addClick = function(eventObject){
		
		var saveURL = $(eventObject.srcElement).siblings('[name="saveURL"]').val();
		alert(saveURL);
		$.ajax({
			type: 'POST',
			url: saveURL,
			data: $(eventObject.srcElement).closest('form').serialize(),
			success: addSuccess,
			error: Utils.AjaxFail,
			dataType: "json"
		});
	};
	
	var addJSONClick = function(eventObject){
		
		var saveURL = $(eventObject.srcElement).siblings('[name="saveJsonURL"]').val();
		alert(saveURL);
		
		var jQForm = $(eventObject.srcElement).closest('form');
		var form = {};
		form.details = {};
		form.mode = $('input[name="mode"]', jQForm).val();
		form.details.name = $('input[name="details.name"]', jQForm).val();
		form.details.description = $('input[name="details.description"]', jQForm).val();
		form.details.dob = $('input[name="details.dob"]', jQForm).val();
		
		$.ajax({
			headers: { 
		        'Accept': 'application/json',
		        'Content-Type': 'application/json' 
		    },
			type: 'POST',
			url: saveURL,
			data: JSON.stringify(form),
			success: addSuccess,
			error: Utils.AjaxFail,
			dataType: "json"
		});
	};
	
	var addSuccess = function(data, textStatus, jqXHR){
		if(data.status=="success"){
			getList();
		} else {
			alert("fail");
		}
	};
	
	return { Init: Init};
})();